<template>
<div>
	<circle-steps :step="2" :steps="steps"></circle-steps>

	<div class="bigtitle" mgt3>
		<div class="bigtitle-title" nobd>收货人信息</div>
	</div>
	<Row :gutter="10">
		<Col v-for="(item, index) in addresses" :key="index" :xs="{ span: 24, offset: 0 }" :sm="{ span: 12, offset: 0 }" :md="{ span: 6, offset: 0 }" mgt2>
			<address-card :value="item" :bd-blue="item.id==model.deliveryAddressId" @on-click="handleSetAddress(item.id)" @on-update="handleGetAllAddresses"></address-card>
		</Col>
		<Col :xs="{ span: 24, offset: 0 }" :sm="{ span: 12, offset: 0 }" :md="{ span: 6, offset: 0 }" mgt2>
			<div h6 pd4 gray3 bd-gray4 linkable @click="showCreateAddressModal=true">
				<p text-center sz3><Icon type="md-add-circle" /></p>
				<p text-center>添加新地址</p>
			</div>
		</Col>
	</Row>

	<div class="bigtitle" mgt3>
		<div class="bigtitle-title" nobd>支付方式</div>
	</div>
	<Row>
		<div w7 bd-gray4 pdx1 mgt2 mgr2 linkable left :bd-blue="model.paymentType==0" @click="model.paymentType=0">
			<p v-if="paymentSetting.canAlipay" sz1 gray1>在线支付</p>
			<p gray3>Online Payment</p>
		</div>
		<div w7 bd-gray4 pdx1 mgt2 mgr2 linkable left :bd-blue="model.paymentType==1" @click="model.paymentType=1">
			<p sz1 gray1>货到付款</p>
			<p gray3>Cash on delivery</p>
		</div>
		<div w7 bd-gray4 pdx1 mgt2 mgr2 linkable left :bd-blue="model.paymentType==2" @click="model.paymentType=2">
			<p v-if="paymentSetting.canBankTransfer" sz1 gray1>银行转账</p>
			<p gray3>Bank transfer</p>
		</div>
	</Row>
	<!-- <div v-if="model.paymentType==2">
		<p gray3 mgt3>卖家账号信息：</p>
		<p lh3 bd-gray4 sz1 mgt1 linkable>
			<span pd2>邮政储蓄银行</span>
			<span pd4>账号：6221 8818 1102 2772 677</span>
			<span pd4>开户名：张朝升</span>
			<Tooltip content="银行卡信息" placement="暂无">
				<Icon type="ios-information-circle-outline" pd2 sz3/>
			</Tooltip>
		</p>
	</div> -->

	<div class="bigtitle" mgt3>
		<div class="bigtitle-title" nobd>配送方式</div>
	</div>
	<p mgt2>
		<Select v-model="model.shippingTemplateId" @on-change="handleShippingTemplateChange" style="width:200px">
			<Option v-for="item in shippingTemplates" :value="item.id" :key="item.id">{{ item.name }}</Option>
		</Select>
		<span sz1 pd2>运费：￥{{currentShippingTemplate.freight}}</span>
	</p>

	<div class="bigtitle" mgt3>
		<div class="bigtitle-title" nobd>商品清单</div>
		<router-link v-if="model.isFromShoppingCart" :to="{name:'mall'}" right>返回购物车修改 ></router-link>
	</div>
	<table cellspacing="0" mgt2 long text-left bd-gray4 nobdb>
		<tr bg-gray4 sz1>
			<td pd1>商品名称</td>
			<td pd1>单价(元)</td>
			<td pd1>数量</td>
			<td pd1>赠送积分</td>
			<td pd1>小计(元)</td>
		</tr>
		<tr v-for="(item, index) in orderCore.commodityCollection.items" :key="index">
			<td pd1 bdb-gray4>
				<order-detail-profile :detail="item"></order-detail-profile>
			</td>
			<td pd1 bdb-gray4>{{formatPrice(item.price)}}</td>
			<td pd1 bdb-gray4>x{{item.count}}</td>
			<td pd1 bdb-gray4>{{item.xpValue * item.count}}</td>
			<td pd1 bdb-gray4>{{formatPrice(item.totalAmount)}}</td>
		</tr>
	</table>

	<div class="bigtitle" mgt3>
		<div class="bigtitle-title" nobd>使用优惠</div>
	</div>
	<Tabs v-model="couponOrXP" mgt1>
        <TabPane label="优惠券" name="coupon"></TabPane>
        <TabPane label="积分" name="xp"></TabPane>
    </Tabs>
	<div v-if="couponOrXP == 'coupon'">
		<Select v-model="model.couponId" @on-change="handleGetOrderCore" style="width:200px">
			<Option v-for="item in coupons" :value="item.id" :key="item.id">{{ item.profile }}</Option>
		</Select>
		<span sz1 pd2>优惠金额：<span red>￥{{currentCoupon.amount}}</span></span>
		<p mgt2>
			<coupon v-if="currentCoupon.id" :value="currentCoupon" style="width:300px;"></coupon>
		</p>
	</div>
	<div v-if="couponOrXP == 'xp'">
		<p>
			<span>使用积分</span>
			<InputNumber v-model="model.usedXPValue" :min="0" :max="member.xpValue" :step="100" @on-change="handleGetOrderCore" mgl2></InputNumber>
			<span gray3>（可用积分{{member.xpValue}}）</span>
		</p>
	</div>

	<div bdt-gray4 mgt4 text-right pd2>
		<p>已选商品 {{orderCore.commodityCollection.totalCount}} 件，合计（不含运费）：￥{{orderCore.commodityCollection.commodityTotalAmount}}</p>
		<p>运费：￥{{orderCore.freight}}</p>
		<p>优惠：-￥{{orderCore.commodityCollection.xpAmount + orderCore.commodityCollection.couponAmount}}</p>
		<p>赠送积分：{{orderCore.commodityCollection.bounsXPValue}}</p>
	</div>
	<div mgt2 bg-gray4 text-right pd2>
		<p sz2>应付总额：<span sz4 red>￥{{orderCore.totalAmount}}</span></p>
		<p gray2>收件人：{{currentAddress.personName}} {{currentAddress.phoneNumber}}</p>
		<p gray2>配送地址：{{currentAddress.province}}{{currentAddress.city}}{{currentAddress.county}}{{currentAddress.detailedAddress}}</p>
	</div>
	<p text-right mgt3>
		<span red mgr2>{{orderCore.errorMessages.join('，')}}</span>
		<span v-if="orderCore.canSubmit" sz3 pdy2 pdx5 bg-red-linkable white @click="handleSubmitOrder">提交订单</span>
		<span v-else sz3 pdy2 pdx5 bg-gray4 disabled>提交订单</span>
	</p>

	<create-address v-model="showCreateAddressModal" @save-success="handleGetAllAddresses"></create-address>
</div>
</template>

<script lang="ts">
import { Component, Vue,Inject, Prop,Watch } from 'vue-property-decorator';
import AbpBase from '../../lib/abpbase'
import CircleSteps from '../../components/common/circle-steps.vue'
import coupon from '../../components/common/coupon.vue'
import AddressCard from '../member/address/address-card.vue'
import OrderDetailProfile from '../../components/common/order-detail-profile.vue'
import CreateAddress from '../member/address/create-address.vue'

@Component({
	components:{CircleSteps, coupon, AddressCard, OrderDetailProfile, CreateAddress }
})
export default class SubmitOrder extends AbpBase{
	showCreateAddressModal:boolean = false;
	model:any = {
		deliveryAddressId: null,
		items: [],
		isFromShoppingCart: true,
		couponId: null,
		usedXPValue: 0,
		shippingTemplateId: null,
		paymentType: 0
	}
	orderCore:any = {
		canSumbit: false,
		errorMessages: [],
		freight: 0,
		totalAmount: 0,
		commodityCollection: {
			hasCoupon: true,
			couponName: "",
			couponAmount: 0,
			usedXPValue: 0,
			xpAmount: 0,
			bounsXPValue: 0,
			totalAmount: 0,
			totalCount: 0,
			items: []
		}
	}
	get paymentSetting() {
		return this.$store.state.setting.settings.payment;
	}
	get member() {
		return this.$store.state.self.member;
	}
    get addresses(){
        return this.$store.state.address.items;
	}
	get currentAddress() {
		return this.addresses.find(elem => elem.id == this.model.deliveryAddressId) || {};
	}
	get steps():Array<string> {
		return [
			"我的购物车",
			"填写核对订单信息",
			"成功提交订单",
			"完成"
		];
	}
	couponOrXP:string = "coupon";
	get shippingTemplates():Array<any> {
		// var templates = this.$store.state.setting.settings.shippingTemplates;
		// var templateType = this.$store.state.setting.settings.ship.shippingTemplateType;
		// var temp = templates.reduce((result, elem) => {
		// 	if(elem.enabled && elem.templateType == templateType) {
		// 		result.push(elem);
		// 	}
		// 	return result;
		// }, []);
		return this.orderCore.canUsedShippingTemplates || [];
	}
	get currentShippingTemplate() {
		return this.shippingTemplates.find(elem => elem.id == this.model.shippingTemplateId) || {};
	}
	get coupons() {
		return this.orderCore.canUsedCoupons || [];
	}
	get currentCoupon() {
		return this.coupons.find(elem => elem.id == this.model.couponId) || {};
	}
	async handleSetAddress(id) {
		this.model.deliveryAddressId = id;
		this.model.shippingTemplateId = null;
		await this.handleGetOrderCore();
	}
	async handleShippingTemplateChange(){
		if(this.model.shippingTemplateId){
			await this.handleGetOrderCore();
		}
	}
	async handleGetOrderCore() {
		var response = await this.post('Order/CalculateOrderData', this.model);
		if(response.success) {
			this.orderCore = response.result;
		}
	}
	async handleSubmitOrder() {
		var response = await this.post('Order/GenerateOrder', this.model);
		if(response.success) {
			if(this.model.paymentType==1) {
				this.$router.push({
					name: 'member-order'
				});
			}else {
				this.$router.push({
					name: 'payment',
					params: {
						ordernumber: response.result.orderNumber
					}
				});
			}
		}
	}
	async handleGetAllAddresses(){
		await this.$store.dispatch('address/getAll');
	}
	async created() {
		var queryModel = this.$route.query.model;
		if(queryModel) {
			var model = JSON.parse(queryModel);
			this.model.items = model.items || [];
			this.model.isFromShoppingCart = model.isFromShoppingCart == 'true' || false;
		}
		await this.handleGetAllAddresses();
		await this.handleGetOrderCore();
		//setTimeout(() => this.handleGetOrderCore(), 1000);
	}
}
</script>
